package com.oasistudio.tk.connector.imp;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import com.taobao.tbw.common.TBWContext;

public class TaobaoShopSearch{
	public static final int TIMEOUT = 10000;
	private String q;//店铺类目关键字
	private int currentPage = 1;//页码
	private int pageSize = 15;//每页记录数

	public TaobaoShopSearch(){
	}
	
	public void setQ(String q){
		this.q = q;
	}
	public void setCurrentPage(int currentPage){
		this.currentPage = currentPage;
	}
	public void setPageSize(int pageSize){
		this.pageSize = pageSize;
	}
	
	//http://shop.m.taobao.com/shop/shop_search.htm?vm=clt
	//&v=androidClient
	//&t=1332984786
	//&ttid=205200
	//&imei=357988023376259
	//&imsi=460023681726461
	//&pageSize=15
	//&q=%E8%BF%9E%E8%A1%A3%E8%A3%99+%E6%96%B0%E6%AC%BE
	//&currentPage=1
	//&appKey=12278902
	public String getApiUrl() {
		StringBuilder sb = new StringBuilder("http://shop.m.taobao.com/shop/shop_search.htm?vm=clt");
		sb.append("&v=androidClient");
		sb.append("&t="+System.currentTimeMillis());
		sb.append("&ttid="+TBWContext.getInstance().getTtid());
		sb.append("&imei="+TBWContext.getInstance().getImei());
		sb.append("&imsi="+TBWContext.getInstance().getImsi());
		sb.append("&pageSize="+pageSize);
		sb.append("&currentPage="+currentPage);
		sb.append("&q="+URLEncoder.encode(q));
		sb.append("&appKey="+TBWContext.getInstance().getAppKey());
		String url = sb.toString();
		System.out.println("TaobaoShopSearchConnector.getApiUrl() url="+url);
		return url;
	}
	
	public TaobaoShopSearch.ShopsInfo syncConnect() {
		try {
			long startTime = System.currentTimeMillis();
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet();
			request.setURI(new URI(getApiUrl()));
			HttpResponse response = client.execute(request);
			ByteArrayOutputStream bs = new ByteArrayOutputStream();
			int i = 0;
			DataInputStream dis = new DataInputStream(response.getEntity().getContent());
			byte[] b = new byte[2048];
			while ((i = dis.read(b, 0, 2048)) != -1) {
				// System.out.println("mellon:ApiConnector.syncConnect() "+i+" bytes response data readed!");
				bs.write(b, 0, i);
				if (System.currentTimeMillis() - startTime > TIMEOUT * 4) {
					bs.reset();
					break;
				}
			}
			return this.syncPaser(bs.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public TaobaoShopSearch.ShopsInfo syncPaser(byte[] all) {
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumFractionDigits(2);
		nf.setMaximumFractionDigits(2);
		ShopsInfo shopsInfo = new ShopsInfo();
		try {
			String str = new String(all, "UTF-8");
			JSONObject jso = new JSONObject(str);
			if (jso.has("itemsArray")) {
				shopsInfo.isSuccess = true;
				JSONArray array = jso.getJSONArray("itemsArray");
				for (int i = 0; i < array.length(); i++) {
					JSONObject shopJSON = array.getJSONObject(i);
					Shop shop = new Shop();
					shop.shopLogoUrl = shopJSON.optString("shopLogoUrl");
					shop.shopTitle = shopJSON.optString("shopTitle");
					shop.location = shopJSON.optString("location");
					shop.isb = shopJSON.optString("isb");
					shop.mainBusiness = shopJSON.optString("mainBusiness");
					shop.shopAuctionSearch = shopJSON.optString("shopAuctionSearch");
					shop.suid = shopJSON.optString("suid");
					if(shopJSON.has("rate")){
						shop.rate = shopJSON.optString("rate");
					}else if(shopJSON.has("bShopType")){
						shop.bShopType = shopJSON.optString("bShopType");
					}
					shopsInfo.shops.add(shop);
				}
			} else {
				shopsInfo.isSuccess = false;
				//shopsInfo.errCode = response.errCode;
				//shopsInfo.errInfo = response.errInfo;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return shopsInfo;
	}

	public static class ShopsInfo {
		public String errCode;
		public String errInfo;
		public Boolean isSuccess;
		public Number totalResults;
		public List<Shop> shops = new ArrayList<Shop>();
	}
	public static class Shop{
		public String shopLogoUrl;
		public String shopTitle;
		public String location;
		public String isb;
		public String rate;//集市店铺
		public String bShopType;//商城店铺
		public String mainBusiness;
		public String shopAuctionSearch;
		public String suid;
		
		public String toString(){
			StringBuilder sb = new StringBuilder();
			sb.append("shopTitle:"+shopTitle);
			sb.append(";location:"+location);
			sb.append(";isb:"+isb);
			return sb.toString();
		}
	}
}



